package cn.lingyangwl.agile.pay.pay.channel.wxpay.utils;

import cn.lingyangwl.framework.core.utils.spring.SpringUtils;
import cn.lingyangwl.agile.pay.constant.IfCodeEnum;
import cn.lingyangwl.agile.pay.pay.model.bo.MchAppConfigContext;
import cn.lingyangwl.agile.pay.pay.model.bo.WxServiceWrapper;
import cn.lingyangwl.agile.pay.pay.model.params.wxpay.WxpayIsvsubMchParams;
import cn.lingyangwl.agile.pay.pay.model.rqrs.ChannelRetMsgExt;
import cn.lingyangwl.agile.pay.pay.service.ConfigContextQueryService;
import com.github.binarywang.wxpay.bean.request.WxPayOrderCloseRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import org.apache.commons.lang3.StringUtils;

/**
 * 【微信支付】支付通道工具包
 *
 * @author shenguangyang
 */
public class WxpayKit {

    /**
     * 放置 isv特殊信息
     */
    public static void putApiIsvInfo(MchAppConfigContext mchAppConfigContext, WxPayOrderCloseRequest req) {

        //不是特约商户， 无需放置此值
        if (!mchAppConfigContext.isIsvsubMch()) {
            return;
        }

        ConfigContextQueryService configContextQueryService = SpringUtils.getBean(ConfigContextQueryService.class);

        WxpayIsvsubMchParams isvsubMchParams =
                (WxpayIsvsubMchParams) configContextQueryService.queryIsvsubMchParams(mchAppConfigContext.getMchNo(), mchAppConfigContext.getAppId(), IfCodeEnum.WXPAY);

        req.setSubMchId(isvsubMchParams.getSubMchId());
        req.setSubAppId(isvsubMchParams.getSubMchAppId());
    }

    /**
     * 构造服务商 + 商户配置  wxPayConfig
     */
    public static WxPayConfig getWxPayConfig(WxServiceWrapper wxServiceWrapper) {
//        return wxServiceWrapper.getWxPayService().getConfig();
        return null;
    }

    public static String appendErrCode(String code, String subCode) {
        return StringUtils.defaultIfEmpty(subCode, code); //优先： subCode
    }

    public static String appendErrMsg(String msg, String subMsg) {

        if (StringUtils.isNotEmpty(msg) && StringUtils.isNotEmpty(subMsg)) {
            return msg + "【" + subMsg + "】";
        }
        return StringUtils.defaultIfEmpty(subMsg, msg);
    }

    public static void commonSetErrInfo(ChannelRetMsgExt channelRetMsgExt, WxPayException wxPayException) {
        channelRetMsgExt.setChannelErrCode(appendErrCode(wxPayException.getReturnCode(), wxPayException.getErrCode()));
        channelRetMsgExt.setChannelErrMsg(appendErrMsg("OK".equalsIgnoreCase(wxPayException.getReturnMsg()) ? null : wxPayException.getReturnMsg(), wxPayException.getErrCodeDes()));

        // 如果仍然为空
        if (StringUtils.isEmpty(channelRetMsgExt.getChannelErrMsg())) {
            channelRetMsgExt.setChannelErrMsg(StringUtils.defaultIfEmpty(wxPayException.getCustomErrorMsg(), wxPayException.getMessage()));
        }
    }


}
